package com.nova.bluetooth.xunFeiSDK.optionalFunction;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIListener;
import com.nova.bluetooth.R;
import com.nova.bluetooth.xunFeiSDK.engine.AiuiEngine;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;
import com.nova.bluetooth.xunFeiSDK.engine.WakeupEngine;
import com.nova.bluetooth.xunFeiSDK.engine.WakeupListener;
import com.nova.bluetooth.xunFeiSDK.recorder.AudioRecorder;
import com.nova.bluetooth.xunFeiSDK.recorder.RecorderFactory;
import com.nova.bluetooth.xunFeiSDK.utils.CopyAssetsUtils;
import com.nova.bluetooth.xunFeiSDK.utils.InteractUtil;
import com.nova.bluetooth.xunFeiSDK.utils.senselessWordUtil;


import java.nio.charset.StandardCharsets;

/**
 * 唤醒后交互一定时间自动进入待唤醒状态
 * 核心代码：
 * 1.InteractUtil中设置唤醒后持续交互的时长 interactTime
 * 2.唤醒时启动定时器 onwakeup回调中执行：InteractUtil.startTimer(mAIUIAgent);
 * 3.收到语义(或识别）结果时重置计时器时间：InteractUtil.resetTimer();
 */
public class InteractCertainTimeActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = InteractCertainTimeActivity.class.getSimpleName();
    Handler handler = new Handler();
    private TextView mResText;
    private ScrollView mScrollView;
    private Button btnStopRecord;
    // AIUI
    private AIUIAgent mAIUIAgent;
    // 多麦克算法库
    private WakeupEngine mWakeupEngine;
    private AudioRecorder recorder;


    /**
     * CAE 回调消息处理
     */
    private WakeupListener onCaeOperatorlistener = new WakeupListener() {

        @Override
        public void onWakeup(int angle, int beam, int score, String keyWord) {
            setText("唤醒成功,angle:" + angle + " beam:" + beam + " score=" + score);
            setText("唤醒词" + keyWord);
            //定时器，唤醒后持续交互一段时间
            InteractUtil.startTimer(btnStopRecord);
            // CAE SDK触发唤醒后给AIUI SDK发送手动唤醒事件：让AIUI SDK置于工作状态
            AiuiEngine.MSG_wakeup(EngineConstants.WAKEUPTYPE_VOICE);
        }
    };
    /**
     * AIUI 回调信息处理
     */
    private AIUIListener mAIUIListener = event -> {
        switch (event.eventType) {
            //本demo只展示特定功能，其他事件处理请参照InteractActivity
            case AIUIConstant.EVENT_RESULT:
                if (event.info.contains("\"sub\":\"nlp")) {
                    //收到语义结果，说明还在交互，重置交互时间
                    InteractUtil.resetTimer();
                    JSONObject cntJson = JSON.parseObject(new String(event.data.getByteArray("0"), StandardCharsets.UTF_8));
                    JSONObject nlpResult = cntJson.getJSONObject("intent");
                    //nlp无结果不处理
                    if (nlpResult.isEmpty()) {
                        return;
                    }
                    //如果只判断asr结果中的无意义词，若nlp先返回就可能被错误判断为无意义词
                    String asrResult = nlpResult.getString("text");
                    EngineConstants.meaningful = senselessWordUtil.isMeaningful_filter1word(asrResult);
                    //无意义词不处理
                    if (!EngineConstants.meaningful) {
                        return;
                    }
                    Log.i(TAG, "nlp result :" + nlpResult);
                    //在线语义结果,rc=0语义理解成功，rc≠0语义理解失败
                    setText(nlpResult.toString());
                }
                break;

            case AIUIConstant.EVENT_STATE:    // 状态事件
                EngineConstants.mAIUIState = event.arg1;
                break;
            default:
                break;
        }
    };


    private void initLayout() {
        findViewById(R.id.init_sdk).setOnClickListener(this);
        findViewById(R.id.btnStartRecord).setOnClickListener(this);
        findViewById(R.id.btnStopRecord).setOnClickListener(this);
        findViewById(R.id.btnSave).setVisibility(View.INVISIBLE);
        ((TextView) findViewById(R.id.myTitle)).setText("唤醒后持续交互一定时间");
        mScrollView = findViewById(R.id.scrollView);
        mResText = findViewById(R.id.res_text);
        btnStopRecord = findViewById(R.id.btnStopRecord);
        btnStopRecord.setText("不可交互状态");
        mResText.append("默认唤醒词：小飞小飞。唤醒后才能识别\n");
        mResText.append("重复唤醒、持续识别结果会刷新可交互时间\n");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asr);
        initLayout();
        // 资源拷贝
        CopyAssetsUtils.portingFile(this);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.init_sdk) {
            initSDK();
        } else if (id == R.id.btnStartRecord) {
            startRecord();
        }

    }

    private void initSDK() {
        //TODO 开发者需要实现生成sn的代码，参考：https://www.yuque.com/iflyaiui/zzoolv/tgftb5
        //注意事项1: sn每台设备需要唯一！！！！WakeupEngine的sn和AIUI的sn要一致
        //注意事项2: 获取的值要保持稳定，否则会重复授权，浪费授权量
        EngineConstants.serialNumber = "iflytek-test";
        Log.i(TAG, "sn : " + EngineConstants.serialNumber);
        //状态初始化
        EngineConstants.isRecording = false;
        EngineConstants.isWriting = false;
        // 初始化AIUI(识别+语义+合成）
        mAIUIAgent = AiuiEngine.getInstance(mAIUIListener);
        if (mAIUIAgent != null) {
            setText("AIUI初始化成功");
        } else {
            setText("AIUI初始化失败");
        }
        //初始化CAE(降噪+唤醒)
        mWakeupEngine = WakeupEngine.getInstance(onCaeOperatorlistener);
        if (mWakeupEngine != null) {
            setText("CAE初始化成功");
        } else {
            setText("CAE初始化失败");
        }

        //初始化录音
        if(recorder==null) {
            recorder = RecorderFactory.getRecorder();
        }
        if (recorder != null) {
            setText("录音机初始化成功");
        } else {
            setText("录音机初始化失败");
        }
    }


    private void startRecord() {
        if (recorder != null) {
            int ret = recorder.startRecord();
            if (0 == ret) {
                setText("开启录音成功！");
            } else if (111111 == ret) {
                setText("异常,AlsaRecorder is null ...");
            } else {
                setText("开启录音失败，请查看/dev/snd/下的设备节点是否有777权限！\nAndroid 8.0 以上需要暂时使用setenforce 0 命令关闭Selinux权限！");
                destroyRecord();
            }
        }
    }

    private void stopRecord() {
        if (recorder != null) {
            recorder.stopRecord();
            setText("停止录音");
        }
    }

    private void destroyRecord() {
        stopRecord();
        recorder = null;
        Log.d(TAG, "destroy is Done!");
    }


    /**
     * 根据scrollView 和子view去测量滑动的位置
     *
     * @param scrollView
     * @param view
     */
    private void scrollToBottom(final ScrollView scrollView, final View view) {

        handler.post(() -> {
            if (scrollView == null || view == null) {
                return;
            }
            // offset偏移量。是指当textview中内容超出 scrollview的高度，那么超出部分就是偏移量
            int offset = view.getMeasuredHeight()
                    - scrollView.getMeasuredHeight();
            if (offset < 0) {
                offset = 0;
            }
            //scrollview开始滚动
            scrollView.scrollTo(0, offset);
        });
    }

    private void setText(final String str) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            mResText.append(str + " \n");
            scrollToBottom(mScrollView, mResText);
        } else {
            runOnUiThread(() -> {
                mResText.append(str + " \n");
                scrollToBottom(mScrollView, mResText);
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EngineConstants.isRecording) {
            stopRecord();
        }
        if (onCaeOperatorlistener != null) {
            onCaeOperatorlistener = null;
        }
        if (mAIUIListener != null) {
            mAIUIListener = null;
        }
        if (recorder != null) {
            recorder = null;
        }
        //销毁AIUI引擎，结束时一定要调用destroy()，否则aiui的navite方法状态异常
        AiuiEngine.destroy();
        //销毁唤醒引擎
        WakeupEngine.destroy();
    }
}